let _config;
let _canvasObject

let updateCanvasState = function () {
    if ((_config.undoStatus === false)) {
        var jsonData = _canvasObject.toJSON();
        var canvasAsJson = JSON.stringify(jsonData);
        if (_config.currentStateIndex < _config.canvasState.length - 1) {
            var indexToBeInserted = _config.currentStateIndex + 1;
            _config.canvasState[indexToBeInserted] = canvasAsJson;
            var numberOfElementsToRetain = indexToBeInserted + 1;
            _config.canvasState = _config.canvasState.splice(0, numberOfElementsToRetain);
        } else {
            _config.canvasState.push(canvasAsJson);
        }
        _config.currentStateIndex = _config.canvasState.length - 1;
    }
}

function init(_canvas) {
    _canvasObject = _canvas;

    _config = {
        canvasState: [],
        currentStateIndex: -1,
        undoStatus: false,
        undoFinishedStatus: 1,
    }

    _canvasObject.on(
        'object:modified', function () {
            updateCanvasState();
        }
    );

    _canvasObject.on(
        'object:added', function () {
            updateCanvasState();
        }
    );
}

function undo() {
    if (_config.undoFinishedStatus) {
        if (_config.currentStateIndex === -1) {
            _config.undoStatus = false;
        }
        else {
            if (_config.canvasState.length >= 1) {
                _config.undoFinishedStatus = 0;
                if (_config.currentStateIndex != 0) {
                    _config.undoStatus = true;
                    _canvasObject.loadFromJSON(_config.canvasState[_config.currentStateIndex - 1], function () {
                        _canvasObject.renderAll();
                        _config.undoStatus = false;
                        _config.currentStateIndex -= 1;
                        _config.undoFinishedStatus = 1;
                    });
                }
                else if (_config.currentStateIndex == 0) {
                    _canvasObject.clear();
                    _config.undoFinishedStatus = 1;
                    _config.currentStateIndex -= 1;
                }
            }
        }
    }
}

export default { init, undo };

